<?php
namespace app\admin\controller;
use think\Db;
/**
 * 算力
 * Class NoticeController
 * Author mww
 * @package app\admin\controller
 */
class SystemController extends CommonController
{
    /**
     * 获得数据
     */
    public function getDatas()
    {
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        $_POST = $this->getDataByCampusid($_POST);
        $_POST['remind_userid'] = session('loginSession')['user_id'];
        $pay = Db::table('ew_remind')
            ->where($_POST)
            ->order('remind_id desc')
            ->limit($rows * ($page - 1), $rows)->select();
        $total = Db::table('ew_remind')
            ->where($_POST)
            ->count();
        $data['total'] = $total;
        $data['rows'] = $pay;
        return json_encode($data);
    }
    /**
     * 获得流水数据
     */
    public function waterDatas()
    {
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        $_POST = $this->getDataByCampusid($_POST);
        $_POST['water_userid'] = session('loginSession')['user_id'];
        if(!empty($_POST['start']) && !empty($_POST['end'])){
            $start = $_POST['start'];
            $end = $_POST['end'];
            unset($_POST['start']);
            unset($_POST['end']);
            $pay = Db::table('ew_water')
                ->where($_POST)
                ->where('water_date','>=',$start)
                ->where('water_date','<=',$end)
                ->order('water_id desc')
                ->limit($rows * ($page - 1), $rows)->select();
            $total = Db::table('ew_water')
                ->where($_POST)
                ->where('water_date','>=',$start)
                ->where('water_date','<=',$end)
                ->count();
        }elseif(!empty($_POST['end']) && empty($_POST['start'])){
            $end = $_POST['end'];
            unset($_POST['end']);
            $pay = Db::table('ew_water')
                ->where($_POST)
                ->where('water_date','<=',$end)
                ->order('water_id desc')
                ->limit($rows * ($page - 1), $rows)->select();
            $total = Db::table('ew_water')
                ->where($_POST)
                ->where('water_date','<=',$end)
                ->count();
        }elseif(empty($_POST['end']) && !empty($_POST['start'])){
            $start = $_POST['start'];
            unset($_POST['start']);
            $pay = Db::table('ew_water')
                ->where($_POST)
                ->where('water_date','>=',$start)
                ->order('water_id desc')
                ->limit($rows * ($page - 1), $rows)->select();
            $total = Db::table('ew_water')
                ->where($_POST)
                ->where('water_date','>=',"$start")
                ->count();
        }else{
            $pay = Db::table('ew_water')
                ->where($_POST)
                ->order('water_id desc')
                ->limit($rows * ($page - 1), $rows)->select();
            $total = Db::table('ew_water')
                ->where($_POST)
                ->count();
        }
        $data['total'] = $total;
        $data['rows'] = $pay;
        return json_encode($data);
    }
    //==========================这是管理员操作分割线==================================
    /**
     * 管理员的参数设置————最重要的第一个
     * 显示修改页面：不让编辑，一天只允许操作一回
     */
    public function show_eth()
    {   $eth = Db::table('ew_eth')->find();
        $today = date('Y-m-d');
        if($eth['eth_date'] == $today){
            return "您今天已经录入过了，不知您是怎么进到这一步的！";
        }else{
            $this->assign('eth',$eth);
            return $this->fetch("system/show_eth");
        }
    }
    //最重要的来了——第一个的第二步！！！！！！
    public function update_eth()
    {
        set_time_limit(0);
        $num = trim($_POST['num'],' ');//return json_encode(['status'=>0,'msg'=>$_POST['num']]);
        $price = trim($_POST['price'],' ');
        if($num == "" || $price == ""){return json_encode(['status'=>0,'msg'=>'不能为空']);}
        $eth = Db::table('ew_eth')->find();
        $today = date('Y-m-d');
        if($eth['eth_date'] == $today){return json_encode(['status'=>0,'msg'=>'今天您已经录入过了']);}
        if($num > $eth['eth_big'] || $num < $eth['eth_small']){return json_encode(['status'=>0,'msg'=>'ETH获得数不在范围内']);}
        $num = substr(sprintf("%.6f", $num),0,-1);
        $price = substr(sprintf("%.3f", $price),0,-1);
        //=================计算开始=====================
        $dataa = array();
        $dataa['eth_number'] = $num;
        $dataa['eth_price'] = $price;
        $dataa['eth_date'] = date('Y-m-d');
        $dataa['eth_time'] = date('Y-m-d H:i:s');
        Db::startTrans();
        try{
            //===============所有的合同天数都减1================
            $sd = Db::table('ew_eth')->where('eth_id',1)->find()['eth_date'];
            $startdate=strtotime($sd);
            $enddate=strtotime(date("Y-m-d"));
            $days=round(($enddate-$startdate)/3600/24);//合同应该减去几天

            //=======================================================
            $dash = array();
            $dash['type'] = 1;$dash['value'] = $num;$dash['date'] = date('Y-m-d');
            Db::table('ew_dash')->insert($dash);
            $dash2 = array();
            $dash2['type'] = 2;$dash2['value'] = $price;$dash2['date'] = date('Y-m-d');
            Db::table('ew_dash')->insert($dash2);
            Db::table('ew_eth')->where('eth_id',1)->update($dataa);
            $user = Db::table('ew_contract')->alias('c')
                ->join('ew_user u','c.con_userid=u.user_id','LEFT')
                ->where('user_auth',1)
                ->where('con_status',1)
                ->field('user_id,user_display,user_rmb,user_ytb,user_phone,user_nickname,con_userid')
                ->group('con_userid')
                ->select();
            $mynum = 0;
            foreach($user as $v){
                //1、更改用户信息
                $userid = $v['user_id'];$dis = $v['user_display'];
                $data = $this->work_computer($userid,$num,$price,$dis);
                $res = array();//1
                $data2 = array();//2、入流水——收益
                $data3 = array();//2、入流水——电费
                $data4 = array();//2、入流水——维护费
                if($dis == 1){
                    $res['user_rmb'] = $v['user_rmb'] + $data['user_rmb'] - $data['dianfei']-$data['weihu'];
                    //===========
                    $data2['water_money'] = $data['user_rmb'];
                    $data2['water_usermoney'] = $v['user_rmb'] + $data['user_rmb'];
                    $data3['water_usermoney'] = $v['user_rmb'] + $data['user_rmb'] - $data['dianfei'];
                    $data4['water_usermoney'] = $res['user_rmb'];
                }else{
                    $res['user_rmb'] = $v['user_rmb'] - $data['dianfei'] - $data['weihu'];
                    $res['user_ytb'] = $v['user_ytb'] + $data['user_ytb'];
                    $data2['water_money'] = $data['user_ytb'];
                    $data2['water_usermoney'] = $res['user_ytb'];
                    $data3['water_usermoney'] = $res['user_ytb'];
                    $data4['water_usermoney'] = $res['user_ytb'];
                }
                Db::table('ew_user')->where('user_id',$userid)->update($res);
                //2、入流水
                $data2['water_userid'] = $userid;
                $data2['water_number'] = 'L' . date('YmdHis') . rand(10000,99999);
                $data2['water_status'] = 1;
                $data2['water_morb'] = $dis;
                $data2['water_type'] = 1;
                $data2['water_date'] = date("Y-m-d");;
                $data2['water_datetime'] = date("Y-m-d H:i:s");
                $data2['water_base'] = $price;
                $data2['water_other'] = $data['other'];//统计损耗
                //=====================
                $data3['water_userid'] = $userid;
                $data3['water_number'] = 'L' . date('YmdHis') . rand(10000,99999);
                $data3['water_status'] = 2;
                $data3['water_morb'] = 1;
                $data3['water_type'] = 2;
                $data3['water_date'] = date("Y-m-d");;
                $data3['water_datetime'] = date("Y-m-d H:i:s");
                $data3['water_base'] = $price;
                $data3['water_money'] = $data['dianfei'];
                //=================================
                $data4['water_userid'] = $userid;
                $data4['water_number'] = 'L' . date('YmdHis') . rand(10000,99999);
                $data4['water_status'] = 2;
                $data4['water_morb'] = 1;
                $data4['water_type'] = 3;
                $data4['water_date'] = date("Y-m-d");
                $data4['water_datetime'] = date("Y-m-d H:i:s");
                $data4['water_base'] = $price;
                $data4['water_money'] = $data['weihu'];
                Db::table('ew_water')->insert($data2);
                if($data3['water_money'] > 0){
                    Db::table('ew_water')->insert($data3);
                }
                if($data4['water_money'] > 0){
                    Db::table('ew_water')->insert($data4);
                }
                $mynum += $data['mynum'];
            }
            //=======统计损耗==================
            $sum_rmb = Db::table('ew_water')->where('water_date',date('Y-m-d'))
                ->where('water_type',1)->where('water_morb',1)->sum('water_money');
            $sum_rmb2 = Db::table('ew_water')->where('water_date',date('Y-m-d'))
                ->where('water_type',1)->where('water_morb',2)->sum('water_other');
            $sum_ytb = Db::table('ew_water')->where('water_date',date('Y-m-d'))
                ->where('water_type',1)->where('water_morb',2)->sum('water_money');
            $sum_ytb2 = Db::table('ew_water')->where('water_date',date('Y-m-d'))
                ->where('water_type',1)->where('water_morb',1)->sum('water_other');
            $sunhao = array();
            $ji = $price*$num;
            $ji2 = $price*$mynum;//人民币损耗是另外一套=====
            $price_sunhao = substr(sprintf("%.3f", $ji2),0,-1);
            $sunhao['date'] = date('Y-m-d');
            $sunhao['rmb'] = $price_sunhao - $sum_rmb - $sum_rmb2;
            $sunhao['rmb'] = substr(sprintf("%.3f", $sunhao['rmb']),0,-1);
            $sunhao['ytb'] = $num - $sum_ytb - $sum_ytb2;
            $sunhao['ytb'] = substr(sprintf("%.6f", $sunhao['ytb']),0,-1);
            $sunhao['eth'] = $num;
            $sunhao['price'] = $price;
            $all_count = Db::table('ew_computer')->where('com_status',1)->sum('com_all');
            $one_count2 = $ji/$all_count;
            $one_count = substr(sprintf("%.3f", $one_count2),0,-1);
            $sunhao['onecount'] = $one_count;
            $sunhao['rmbout'] = $sum_rmb;
            $sunhao['ytbout'] = $sum_ytb;
            $dianfei = Db::table('ew_water')->where('water_date',date('Y-m-d'))
                ->where('water_type',2)->sum('water_money');
            $weihufei = Db::table('ew_water')->where('water_date',date('Y-m-d'))
                ->where('water_type',3)->sum('water_money');
            $sunhao['dianfei'] = $dianfei;
            $sunhao['weihufei'] = $weihufei;
            Db::table('ew_admin_loss')->insert($sunhao);
            //=======统计损耗end===============
            //============更新前台的两个产品价格信息start====================
            Db::table('ew_home')->where('id',1)->update(['shouyi'=>$one_count]);
            Db::table('ew_home')->where('id',2)->update(['shouyi'=>$one_count*10]);
            //============更新前台的两个产品价格信息end====================
            //============================结算完之后再算合同天数==========================
            $all_cons = Db::table('ew_contract')->alias('con')
                ->join('ew_user u','con.con_userid=u.user_id','LEFT')
                ->where('con_status',1)
                ->field('con_id,con_days,user_phone,user_nickname,con_number')->select();
            foreach ($all_cons as $kcc=>$vcc){
                $last = array();
                $last['con_days'] = $vcc['con_days']-$days;
                if($vcc['con_days']-$days <= 0){
                    $last['con_status'] = 2;
                    //把此合同的矿机份额返回去
                    $ccs = Db::table('ew_contract_com')->where('cc_contractid',$vcc['con_id'])->select();
                    if(!empty($ccs)){
                        foreach ($ccs as $comv){
                            $comid = $comv['cc_computerid'];
                            $commany = $comv['cc_many'];
                            $com = Db::table('ew_computer')->where('com_id',$comid)->find();
                            $haveee = $com['com_have']+$commany;
                            $useee = $com['com_use']-$commany;
                            Db::table('ew_computer')->where('com_id',$comid)
                                ->update(['com_have'=>$haveee,'com_use'=>$useee]);
                        }
                    }
                    //告诉用户你的合同到期了
                    $this->duanxin($vcc['user_phone'],8,$vcc['user_nickname'],$vcc['con_number'],'已到期');
                }
                Db::table('ew_contract')->where('con_id',$vcc['con_id'])->update($last);
            }
            //======================================================
            // 提交事务
            Db::commit();
            foreach($user as $vv){
                if($vv['user_phone'] != ""){
                    $data = $this->work_computer($vv['user_id'],$num,$price,$vv['user_display']);
                    if($vv['user_display'] == 1){
                        $one1 = $vv['user_rmb'] + $data['user_rmb'] - $data['dianfei']-$data['weihu'];
                        $this->duanxin($vv['user_phone'],6,$vv['user_nickname'],date("Y-m-d",strtotime("-1 day")),$data['user_rmb'],$one1,$vv['user_ytb']);
                    }else{
                        $one1 = $vv['user_rmb'] - $data['dianfei']-$data['weihu'];
                        $one2 = $vv['user_ytb'] + $data['user_ytb'];
                        $this->duanxin($vv['user_phone'],5,$vv['user_nickname'],date("Y-m-d",strtotime("-1 day")),$data['user_ytb'],$one1,$one2);
                    }
                }
            }
            return json_encode(['status'=>200,'msg'=>'设置成功，收益结算已完成']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'操作失败，请联系管理员']);
        }
    }
//后面的几个设置——无伤大雅
    public function show_html()
    {
        $type = $_POST['type'];
        if($type == 1){
            $data = Db::table('ew_eth')->find();
        }elseif($type == 2){
            $data = Db::table('ew_two')->find();
        }elseif($type == 3){
            $data = Db::table('ew_three')->find();
        }elseif($type == 4){
            $data = Db::table('ew_four')->find();
        }else{
            $data = Db::table('ew_duanxin')->where('id',13)->find();
        }

        $this->assign('data',$data);
        $this->assign('type',$type);
        return $this->fetch("system/show_html");
    }

    public function update_four()
    {
        foreach ($_POST as $key => $value) {
            $value = trim($value,' ');
            if($value == ""){
                return json_encode(['status'=>0,'msg'=>'有未填项']);
            }
        }
        $type = $_POST['type'];
        unset($_POST['type']);
        if($type == 1){
            $_POST['eth_small'] = substr(sprintf("%.6f", $_POST['eth_small']),0,-1);
            $_POST['eth_big'] = substr(sprintf("%.6f", $_POST['eth_big']),0,-1);
            $data = Db::table('ew_eth')->where('eth_id',1)->update($_POST);
        }elseif($type == 2){
            $_POST['date_time'] = date('Y-m-d H:i:s');
            $data = Db::table('ew_two')->where('id',1)->update($_POST);
        }elseif($type == 3){
            $_POST['date_time'] = date('Y-m-d H:i:s');
            $data = Db::table('ew_three')->where('id',1)->update($_POST);
        }elseif($type == 4){
            $_POST['date_time'] = date('Y-m-d H:i:s');
            $data = Db::table('ew_four')->where('id',1)->update($_POST);
        }else{
            $_POST['ddtt'] = date('Y-m-d H:i:s');
            $data = Db::table('ew_duanxin')->where('id',13)->update($_POST);
        }
        if($data){
            return json_encode(['status'=>200,'msg'=>'修改成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'修改失败']);
        }

    }



    /**
     * 获得所有流水数据
     */
    public function adminwaterDatas()
    {
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        $min = '2000-02-02';
        $max = '2050-12-12';
        $where = array();
        $_POST = $this->getDataByCampusid($_POST);
        if(!empty($_POST['start'])){
            $min = $_POST['start'];
            unset($_POST['start']);
        }
        if(!empty($_POST['end'])){
            $max = $_POST['end'];
            unset($_POST['end']);
        }
        $where['water_date'] = array('between',"$min,$max");
        $pay = Db::table('ew_water')->alias('w')
            ->join('ew_user u','w.water_userid=u.user_id','LEFT')
            ->where($_POST)->where($where)
            ->order('water_id desc')
            ->limit($rows * ($page - 1), $rows)->select();
        $total = Db::table('ew_water')->alias('w')
            ->join('ew_user u','w.water_userid=u.user_id','LEFT')
            ->where($_POST)->where($where)
            ->count();
        $data['total'] = $total;
        $data['rows'] = $pay;
        return json_encode($data);
    }
}